﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EventReminder.Common;

namespace EventReminder.Client
{
    internal partial class LoginDialog : Form
    {
        private EventReminderController _controller;

        public LoginDialog()
            : this(null)
        { }

        public LoginDialog(EventReminderController eventReminderController)
        {
            this._controller = eventReminderController;
            _controller.LoginSucceeded += new EventHandler(HandleLoginSucceeded);
            _controller.LoginFailed += new EventHandler(HandleLoginFailed);

            InitializeComponent();
        }

        private void HandleBtnLogin_Click(object sender, EventArgs e)
        {
            _controller.AttemptLogin(txtUsername.Text, txtPassword.Text);
        }

        private void HandleBtnRegister_Click(object sender, EventArgs e)
        {
            _controller.OpenRegisterDialog();
        }

        private void HandleBtnQuit_Click(object sender, EventArgs e)
        {
            _controller.Logout();
        }

        private void HandleLoginSucceeded(object sender, EventArgs args)
        {
            if (this.Visible)
            {
                // NOTE!  This is the MVC model behavior!  Stop having _controller close dialogs!
                Close();
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            _controller.LoginSucceeded -= new EventHandler(HandleLoginSucceeded);
            _controller.LoginFailed -= new EventHandler(HandleLoginFailed);
            base.OnClosed(e);
        }

        private void HandleLoginFailed(object sender, EventArgs args)
        {
            MessageBox.Show("Invalid username or password!");
        }

        private void LoginDialog_Shown(object sender, EventArgs e)
        {
            txtUsername.Focus();
        }
    }
}
